using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using IGlobalist.Chat.Engine;
using System.Web.Script.Services;
using System.Web.Script;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using IGlobalist.Chat.Engine;
using IGlobalist.Chat.Engine.Common;
using IGlobalist.Cms.Common;

namespace IGlobalist.Cms.Chat
{
    public partial class Chat : ChatBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[SessionVariable.Chat.CurrentUserName] == null)
                Response.Redirect("Default.aspx");
            if (string.IsNullOrEmpty(Request.QueryString["rid"]))
                Response.Redirect("Default.aspx");

            txtMsg.Attributes.Add("onkeypress", "return chatClient.clickButton(event,'btn')");
            if (!IsPostBack)
            {
                hdnRoomID.Value = Request.QueryString["rid"];
                Room room = GetChatRoom(hdnRoomID.Value);
                ChatEngine.AddOrGetRoom(room);

                string userName = Session[SessionVariable.Chat.CurrentUserName].ToString();
                User user = new User(GetUserID(userName, room.ID), userName, UserType.Guest);
                string prevMsgs = "";
                try
                {
                    room.JoinRoom(user);
                }
                catch { }

                lblCurrentUser.Text = userName;
                lblRoomName.Text = room.Name;
                ltrMessage.Text = string.Format(ltrMessage.Text, prevMsgs);
                hdnReceiver.Value = room.Administrator.UserName;
                hdnCurrentAccount.Value = userName;
                this.Title = userName;
                foreach (string s in room.GetRoomUsersNames())
                {
                    lstMembers.Items.Add(new ListItem(s, s));
                }
                Session[SessionVariable.Chat.CurrentUser] = user;

            }


        }


        #region Script Callback functions



        /// <summary>
        /// This function is called from the client script 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="roomID"></param>
        /// <returns></returns>
        [WebMethod]
        static public Message[] SendMessage(string msg, string roomID)
        {
            try
            {
                Room room = IGlobalist.Chat.Engine.ChatEngine.GetRoom(roomID);
                Message[] res = null;// new string[2][];

                // return res;
                if (room != null)
                {
                    res = room.SendMessage(msg, CurrentUserID, room.Administrator.UserName, MsgType.Private);

                }
                return res;
            }
            catch (Exception ex)
            {

            }
            return new Message[0];
        }
        /// <summary>
        /// This function is called peridically called from the user to update the messages
        /// </summary>
        /// <param name="otherUserID"></param>
        /// <returns></returns>
        [WebMethod]
        static public Message[] UpdateUser(string roomID)
        {
            try
            {
                Room room = IGlobalist.Chat.Engine.ChatEngine.GetRoom(roomID);
                if (room != null)
                {

                    if (room != null)
                    {
                        return room.UpdateUser(CurrentUserID);
                    }

                }
            }
            catch (Exception ex)
            {

            }
            return new Message[0];
        }


        /// <summary>
        /// This function is called from the client when the user is about to leave the room
        /// </summary>
        /// <param name="otherUser"></param>
        /// <returns></returns>
        [WebMethod]
        static public string LeaveRoom(string roomID)
        {
            try
            {
                Room room = IGlobalist.Chat.Engine.ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    room.LeaveRoom(CurrentUserID);
                    SerializeData(room);
                }
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        public static void SerializeData(Room room)
        {
            if (room.Messages == null)
                return;

            string path = Path.Combine(ArchivePhysicalPath, "data.dat");
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            try
            {
                bf.Serialize(fs, room.Messages);
            }
            catch (Exception ex)
            {
                // SharedInfo.Logger.Error("", ex);
            }
            fs.Flush();
            fs.Close();

        }



        /// <summary>
        /// Returns a comma separated string containing the names of the users currently online
        /// </summary>
        /// <param name="roomID"></param>
        /// <returns></returns>
        [WebMethod]
        static public string UpdateRoomMembers(string roomID)
        {
            try
            {
                Room room = IGlobalist.Chat.Engine.ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    IEnumerable<string> users = room.GetRoomUsersNames();
                    string res = "";

                    foreach (string s in users)
                    {
                        res += s + ",";
                    }
                    return res;
                }
            }
            catch (Exception ex)
            {
            }
            return "";
        }
        #endregion
    }
}
